/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package almacen;

import resources.local_connection;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.border.TitledBorder;
import resources.queries;

/**
 *
 * @author Tesla
 */
public class almacenado extends javax.swing.JFrame {

    Connection cn;
    PreparedStatement ps;
    ResultSet rs;
    int laOtraSuc=0;
    static int code;
    int id_proveedor;
    boolean G_addNewStock;

    /**
     * Creates new form almacenado
     * @param cd
     */
    public almacenado(int cd) {
        initComponents();
        G_addNewStock = false;
        code = cd;
        int total_stock = 0;
        try {
            cn = local_connection.getconnect();
            ps = (PreparedStatement) cn.prepareStatement("SELECT a.id_producto,a.cantidad,a.minimo,a.sucursal,a.ubicacion,b.nombre,b.id FROM stock a LEFT OUTER JOIN sucursales b ON (a.sucursal = b.id)  WHERE id_producto = "+code+" AND (sucursal = "+Almacen.suc1+" OR sucursal="+Almacen.suc2+")");
            rs = ps.executeQuery();
            TitledBorder title = BorderFactory.createTitledBorder("NULL");
            if(rs.next()){
                title = BorderFactory.createTitledBorder(rs.getString("nombre"));
                panelSuc1.setBorder(title);
                textStockSuc1.setText(rs.getString("cantidad"));
                textMinStockSuc1.setText(rs.getString("minimo"));
                textUbicSuc1.setText(rs.getString("ubicacion"));
                total_stock += rs.getInt("cantidad");
                laOtraSuc=rs.getInt("id");
            }
            if(rs.next()){
                title = BorderFactory.createTitledBorder(rs.getString("nombre"));
                panelSuc2.setBorder(title);
                textStockSuc2.setText(rs.getString("cantidad"));
                textMinStockSuc2.setText(rs.getString("minimo"));
                textUbicSuc2.setText(rs.getString("ubicacion"));
                total_stock += rs.getInt("cantidad");
            } else if (Almacen.suc1 == Almacen.suc2) {
                panelSuc2.setBorder(panelSuc1.getBorder());
                textStockSuc2.setText(textStockSuc1.getText());
                textMinStockSuc2.setText(textMinStockSuc1.getText());
                textUbicSuc2.setText(textUbicSuc1.getText());            
            } else {
                G_addNewStock = true;
                if(Almacen.suc1 == laOtraSuc) laOtraSuc = Almacen.suc2;                
                else laOtraSuc = Almacen.suc1;
                ps = (PreparedStatement) cn.prepareStatement("SELECT nombre FROM sucursales WHERE id="+laOtraSuc+" LIMIT 1");
                rs = ps.executeQuery();
                rs.next();
                title = BorderFactory.createTitledBorder(rs.getString("nombre"));
                panelSuc2.setBorder(title);
                textStockSuc2.setText("2");
                textMinStockSuc2.setText("2");
                textUbicSuc2.setText("");
            }
            textStockTotal.setText(Integer.toString(total_stock));
            textProductId.setText("Id de producto: "+Integer.toString(code));
        } catch (SQLException e) {
Almacen.logger.log(Level.SEVERE, null, e);        }
    }

    private void insertarRevision(){
            try {
                ps = (PreparedStatement) cn.prepareStatement("SELECT * FROM revisiones WHERE idProducto = " + code);
                rs = ps.executeQuery();
                int id = (int) code;
                DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
                Date date = (Date) new Date();
                if(rs.isBeforeFirst()){
                    ps = (PreparedStatement) cn.prepareStatement("UPDATE revisiones SET fecha = ? WHERE idProducto = "+id);
                    ps.setString(1,dateFormat.format(date));
                } else {
                    date = new Date();
                    ps = (PreparedStatement) cn.prepareStatement("INSERT INTO revisiones(idProducto,cantidadalmacen,cantidad_stock,fecha) VALUES(?,?,?,?)");
                    ps.setInt(1,id);
                    ps.setString(4,dateFormat.format(date));
                }                
                ps.execute();
            } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);            }        
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        textStockTotal = new javax.swing.JLabel();
        buttonSalir = new javax.swing.JButton();
        panelSuc1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        textStockSuc1 = new javax.swing.JTextField();
        textMinStockSuc1 = new javax.swing.JTextField();
        textUbicSuc1 = new javax.swing.JTextField();
        panelSuc2 = new javax.swing.JPanel();
        textUbicSuc2 = new javax.swing.JTextField();
        textMinStockSuc2 = new javax.swing.JTextField();
        textStockSuc2 = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        buttonGuardar = new javax.swing.JButton();
        textProductId = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Stocks");
        setIconImage(new ImageIcon(getClass().getResource("/resources/logo_rayito.png")).getImage());

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel1.setText("Stock en ambas sucursales:");

        textStockTotal.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        textStockTotal.setText("----");

        buttonSalir.setText("Salir");
        buttonSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSalirActionPerformed(evt);
            }
        });

        panelSuc1.setBorder(javax.swing.BorderFactory.createTitledBorder("Sucursal1"));

        jLabel2.setText("Stock:");

        jLabel3.setText("Ubicacion:");

        jLabel4.setText("Minimo de Stock:");

        textStockSuc1.setText("0");
        textStockSuc1.setNextFocusableComponent(textMinStockSuc1);
        textStockSuc1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textStockSuc1ActionPerformed(evt);
            }
        });

        textMinStockSuc1.setText("0");
        textMinStockSuc1.setNextFocusableComponent(textUbicSuc1);

        textUbicSuc1.setNextFocusableComponent(textStockSuc2);

        javax.swing.GroupLayout panelSuc1Layout = new javax.swing.GroupLayout(panelSuc1);
        panelSuc1.setLayout(panelSuc1Layout);
        panelSuc1Layout.setHorizontalGroup(
            panelSuc1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelSuc1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelSuc1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelSuc1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(textStockSuc1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelSuc1Layout.createSequentialGroup()
                        .addGroup(panelSuc1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(panelSuc1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(textUbicSuc1)
                            .addComponent(textMinStockSuc1, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE))))
                .addContainerGap())
        );
        panelSuc1Layout.setVerticalGroup(
            panelSuc1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelSuc1Layout.createSequentialGroup()
                .addGroup(panelSuc1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(textStockSuc1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelSuc1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textMinStockSuc1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
                .addGroup(panelSuc1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(textUbicSuc1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        panelSuc2.setBorder(javax.swing.BorderFactory.createTitledBorder("Sucursal2"));

        textUbicSuc2.setNextFocusableComponent(buttonGuardar);

        textMinStockSuc2.setText("0");
        textMinStockSuc2.setNextFocusableComponent(textUbicSuc2);

        textStockSuc2.setText("0");
        textStockSuc2.setNextFocusableComponent(textMinStockSuc2);

        jLabel6.setText("Minimo de Stock:");

        jLabel7.setText("Ubicacion:");

        jLabel8.setText("Stock:");

        javax.swing.GroupLayout panelSuc2Layout = new javax.swing.GroupLayout(panelSuc2);
        panelSuc2.setLayout(panelSuc2Layout);
        panelSuc2Layout.setHorizontalGroup(
            panelSuc2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelSuc2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelSuc2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelSuc2Layout.createSequentialGroup()
                        .addComponent(jLabel8)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(textStockSuc2, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelSuc2Layout.createSequentialGroup()
                        .addGroup(panelSuc2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6)
                            .addComponent(jLabel7))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(panelSuc2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(textUbicSuc2)
                            .addComponent(textMinStockSuc2, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE))))
                .addContainerGap())
        );
        panelSuc2Layout.setVerticalGroup(
            panelSuc2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelSuc2Layout.createSequentialGroup()
                .addGroup(panelSuc2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(textStockSuc2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelSuc2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textMinStockSuc2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
                .addGroup(panelSuc2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(textUbicSuc2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        buttonGuardar.setText("Guardar");
        buttonGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonGuardarActionPerformed(evt);
            }
        });

        textProductId.setText("Producto:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(buttonGuardar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buttonSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(textProductId)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(58, 58, 58)
                                .addComponent(textStockTotal)))
                        .addGap(0, 16, Short.MAX_VALUE))
                    .addComponent(panelSuc1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(panelSuc2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(textStockTotal, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(textProductId)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelSuc1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelSuc2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonSalir)
                    .addComponent(buttonGuardar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSalirActionPerformed
        this.dispose();
        // TODO add your handling code here:
    }//GEN-LAST:event_buttonSalirActionPerformed

    private void buttonGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonGuardarActionPerformed
        if(textStockSuc1.getText().isEmpty()) textStockSuc1.setText("0");
        if(textMinStockSuc1.getText().isEmpty()) textMinStockSuc1.setText("0");
        if(textStockSuc2.getText().isEmpty()) textStockSuc2.setText("0");
        if(textMinStockSuc2.getText().isEmpty()) textMinStockSuc2.setText("0");
        
        queries.doSyncQuery(cn, ps, "UPDATE stock SET cantidad="+textStockSuc1.getText()+",ubicacion='"+textUbicSuc1.getText()+"',minimo="+textMinStockSuc1.getText()+" WHERE id_producto=" +code+" AND sucursal = "+Almacen.suc1); 
        if(Almacen.suc1 != Almacen.suc2){
            if(G_addNewStock == true)
                queries.doSyncQuery(cn, ps, "INSERT INTO stock(id_producto,cantidad,ubicacion,sucursal,minimo) VALUES ("+code+","+textStockSuc2.getText()+",'"+textUbicSuc2.getText()+"',"+laOtraSuc+","+textMinStockSuc2.getText()+")");
            else                
                queries.doSyncQuery(cn, ps, "UPDATE stock SET cantidad="+textStockSuc2.getText()+",ubicacion='"+textUbicSuc2.getText()+"',minimo="+textMinStockSuc2.getText()+" WHERE id_producto=" +code+" AND sucursal = "+Almacen.suc2); 
        }
        insertarRevision();
        this.dispose();
    }//GEN-LAST:event_buttonGuardarActionPerformed

    private void textStockSuc1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textStockSuc1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_textStockSuc1ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonGuardar;
    private javax.swing.JButton buttonSalir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel panelSuc1;
    private javax.swing.JPanel panelSuc2;
    private javax.swing.JTextField textMinStockSuc1;
    private javax.swing.JTextField textMinStockSuc2;
    private javax.swing.JLabel textProductId;
    private javax.swing.JTextField textStockSuc1;
    private javax.swing.JTextField textStockSuc2;
    private javax.swing.JLabel textStockTotal;
    private javax.swing.JTextField textUbicSuc1;
    private javax.swing.JTextField textUbicSuc2;
    // End of variables declaration//GEN-END:variables
}
